import { Injectable, OnModuleInit } from '@nestjs/common'
import { connect, MqttClient } from 'mqtt'
import { ConfigService } from '@donews/nestjs-config'
import { CustomLoggerService } from '@/modules'

@Injectable()
export class MqttService implements OnModuleInit {
    private mqtt: MqttClient
    private retry = 0
    constructor(private readonly config: ConfigService, private readonly logger: CustomLoggerService) {}

    public async onModuleInit() {
        const option = this.config.get('mqtt', {
            url: 'mqtt://localhost:1883',
            options: {
                clientId: 'micro-fire',
                username: 'micro-fire',
            },
        })
        this.mqtt = connect(option.url, option.options)
        this.mqtt.on('connect', (e) => {
            this.logger.info(`[MqttService] - MQTT链接成功！`)
            this.retry = 0
        })
        this.mqtt.on('error', (e) => {
            this.logger.error(`[MqttService] - MQTT链接失败！ - ${e}`)
        })
    }

    public pubMessage(topic: string, message) {
        if (!topic) {
            this.logger.error(`[MqttService] - pubMessage - topic不可为空！`)
            return
        }
        this.logger.info(`[MqttService] - pubMessage - ${topic} - ${message.id}`)
        switch (typeof message) {
            case 'object':
                this.mqtt.publish(topic, JSON.stringify(message))
                break
            case 'string':
                this.mqtt.publish(topic, message)
                break
            default:
                this.logger.error(`[MqttService] - pubMessage - ${typeof message}`)
                break
        }
    }
}
